const path=require('path')
const fs=require('fs')
const serve = require('koa-static');
const Koa=require('koa2')
const xlsx = require('xlsx');
const app=new Koa()
const router=require("../router/index")
const  KoaStart=require('koa-static')
const koaParameter=require('koa-parameter')
const { koaBody } = require('koa-body');
const multer = require('koa-multer');
const cors = require('koa-cors');
const { log } = require('console');
app.use(cors());
app.use(koaBody({multipart:true,
    formidable:{
        uploadDir:path.join(__dirname,'../upload'),
        keepExtensions:true
    }}));
app.use(koaParameter(app))
app.use(serve(path.join(__dirname, '../upload')));
app.use(KoaStart(path.join(__dirname,'../upload')))
app.use(router.routes()).use(router.allowedMethods())
// 错误处理
app.on('err',(err,ctx)=>{
    ctx.body=err
})


// 创建上传目录
const createDirectoryIfNotExists = (dir) => {
    if (!fs.existsSync(dir)){
        fs.mkdirSync(dir, { recursive: true });
    }
};

const tempDir = path.join(__dirname, '../uploads/temp');
const permanentDir = path.join(__dirname, '../uploads/permanent');

// 创建目录
createDirectoryIfNotExists(tempDir);
createDirectoryIfNotExists(permanentDir);
// 配置 multer 存储
const storageTemp = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, tempDir);
    },
    filename: (req, file, cb) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const ext = path.extname(file.originalname);
        cb(null, file.fieldname + '-' + uniqueSuffix + ext);
    }
});

const storagePermanent = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, permanentDir);
    },
    filename: (req, file, cb) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const ext = path.extname(file.originalname);
        cb(null, file.fieldname + '-' + uniqueSuffix + ext);
    }
});

// 初始化 multer
const uploadTemp = multer({ storage: storageTemp });
const uploadPermanent = multer({ storage: storagePermanent });

// // 添加书籍
// const BookTser = require("../model/booksTest.model")
// const file  = path.join(__dirname, '../excel/11.xlsx');
// console.log(file,11)

// const workbook = xlsx.readFile(file);
// const sheetName = workbook.SheetNames[0]; // 读取第一个工作表
// const worksheet = workbook.Sheets[sheetName];

// // 将 Excel 数据转换为 JSON
// const data = xlsx.utils.sheet_to_json(worksheet);
//  for (const row of data) {
//     for (let i = 0; i < row.num; i++) { // 根据 num 列插入多条数据
     
//         try {
//             const res=  BookTser.create({
//                 title: row.title,
//                 author: row.author,
//                 publisher: row.publisher,
//                 publish_year: row.publish_year,
//                 source: row.source,
//                 category: row.category,
                
//             });
         
//         } catch (err) {
//             console.log("错误",err)
//         }
//     }
// }
module.exports = app

